package com.xust.oa.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xust.oa.domain.dto.AdminDTO;
import com.xust.oa.domain.dto.LoginDTO;
import com.xust.oa.domain.entity.TAdmin;
import com.xust.oa.domain.entity.TDepartment;
import com.xust.oa.domain.entity.TPosition;
import com.xust.oa.domain.vo.AdminVo;
import com.xust.oa.domain.vo.UserVO;
import com.xust.oa.mapper.TAdminMapper;
import com.xust.oa.service.TAdminService;
import com.xust.oa.service.TDepartmentService;
import com.xust.oa.service.TPositionService;
import com.xust.oa.utils.JwtUtil;
import com.xust.oa.utils.Result;
import com.xust.oa.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZHANGJIE
 * @description 针对表【t_admin】的数据库操作Service实现
 * @createDate 2025-03-25 09:24:09
 */
@Service
public class TAdminServiceImpl extends ServiceImpl<TAdminMapper, TAdmin>
        implements TAdminService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private TPositionService positionService;

    @Autowired
    private TDepartmentService departmentService;


    @Autowired
    private TAdminMapper AdminMapper;

    @Override
    public Result login(LoginDTO loginDTO) {

        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        MD5 md5 = new MD5();
        String md5Password = md5.digestHex16(password);
        QueryWrapper<TAdmin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        queryWrapper.eq("password", md5Password);
        TAdmin admin = getOne(queryWrapper);
        if (admin != null) {
            admin.setPassword(null);
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(admin, userVO);
            UserHolder.saveUser(userVO);
            // 系统暂时默认都为系统管理员
            String token = JwtUtil.getToken(admin.getId().toString(), "admin");
            redisTemplate.opsForValue().set("OAUser:token:" + admin.getId(), token);
            return Result.ok(token);
        }
        return Result.buildFailure(401, "用户名或密码错误");
    }

    @Override
    public Result<List<AdminVo>> getList(AdminDTO adminDTO) {
        Integer pageNum = adminDTO.getPageNum();
        if (pageNum == null || pageNum < 1) pageNum = 1;
        Integer pageSize = adminDTO.getPageSize();
        if (pageSize == null || pageSize < 1) pageSize = 10;
        Page<TAdmin> page = new Page<>(pageNum, pageSize);


        QueryWrapper<TAdmin> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(adminDTO.getUsername()))
            queryWrapper.like("name", adminDTO.getUsername());
        if (!StringUtils.isEmpty(adminDTO.getDeptName()))
            queryWrapper.eq("dept_id", getDeptId(adminDTO.getDeptName()));
        if (!StringUtils.isEmpty(adminDTO.getPositionName()))
            queryWrapper.eq("position_id", getPositionId(adminDTO.getPositionName()));
        if (!StringUtils.isEmpty(adminDTO.getEnabled()))
            queryWrapper.eq("enabled", adminDTO.getEnabled());

        // 执行分页查询
        IPage<TAdmin> pageResult = AdminMapper.selectPage(page, queryWrapper);

// 获取分页结果中的数据列表
        List<TAdmin> list = pageResult.getRecords();

        List<AdminVo> listVo = new ArrayList<>();
//        BeanUtils.copyProperties(list, listVo);
        QueryWrapper<TPosition> positionQueryWrapper = new QueryWrapper<>();
        positionQueryWrapper.eq("enabled", 1);
        List<TPosition> tPositions = positionService.list(positionQueryWrapper);

        QueryWrapper<TDepartment> departmentQueryWrapper = new QueryWrapper<>();
        departmentQueryWrapper.eq("enabled", 1);
        List<TDepartment> departmentList = departmentService.list();
        Map<Integer, String> positionMap = tPositions.stream()
                .collect(java.util.stream.Collectors.toMap(TPosition::getId, TPosition::getName));
        Map<Integer, String> deptMap = departmentList.stream()
                .collect(java.util.stream.Collectors.toMap(TDepartment::getId, TDepartment::getName));
        for (TAdmin tAdmin : list) {
            AdminVo adminVo = new AdminVo();
            BeanUtils.copyProperties(tAdmin, adminVo);
            adminVo.setPositionName(positionMap.get(tAdmin.getPositionId()));
            adminVo.setDeptName(deptMap.get(tAdmin.getDeptId()));
            listVo.add(adminVo);
        }

        return Result.ok(listVo);
    }

    private Integer getDeptId(String deptName) {
        List<TDepartment> departmentList = departmentService.list();
        Map<String,Integer> deptMap = new HashMap<>();
        for (TDepartment department : departmentList) {
            deptMap.put(department.getName(),department.getId());
        }
        return deptMap.get(deptName);
    }

    private Integer getPositionId(String positionName) {
        List<TPosition> positionList = positionService.list();
        Map<String,Integer> positionMap = new HashMap<>();
        for (TPosition position : positionList) {
            positionMap.put( position.getName(),position.getId());
        }
        return positionMap.get(positionName);
    }

}




